package net.chanibal.hala.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.InvocationException;
import com.google.gwt.user.client.rpc.SerializableException;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PushButton;

import net.chanibal.hala.client.Imprezy;

import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.VerticalSplitPanel;
import com.google.gwt.user.client.ui.Widget;
import net.chanibal.hala.client.LoginForm;
import net.chanibal.hala.client.AbstractForm.PasswordField;
import net.chanibal.hala.client.Server.KlientData;


/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Login implements EntryPoint,HistoryListener 
{
	private Hyperlink hyperlink_3;
	private Hyperlink hyperlink_2;
	private Hyperlink adminHyperlink;
	private Hyperlink hyperlink_1;
	private VerticalPanel verticalPanel_1;
	private DisclosurePanel disclosurePanel;
	private HorizontalPanel podpanel;
	private Hyperlink registerHyperlink;
	private Hyperlink hyperlink;
	private SimplePanel simplePanel;
	private SimplePanel centerPanel;
	private VerticalPanel verticalPanel;
	private DockPanel dockPanel;
	
	static String refergoto = null;
	
	static boolean isLogined = false;
	static boolean isAdmin = false;
	
	public void onModuleLoad() {
		RootPanel rootPanel = RootPanel.get();

		dockPanel = new DockPanel();
		rootPanel.add(dockPanel, 0, 0);
		dockPanel.setWidth("100%");

		simplePanel = new SimplePanel();
		dockPanel.add(simplePanel, DockPanel.NORTH);

		final HTML html = new HTML("");
		simplePanel.setWidget(html);
		html.setSize("100%", "200px");

		podpanel = new HorizontalPanel();
		dockPanel.add(podpanel, DockPanel.NORTH);
		podpanel.setStyleName("informacjeologowaniu");
		podpanel.setWidth("100%");

		final Label label = new Label("   Trwa pobieranie informacji...   ");
		podpanel.add(label);

		verticalPanel = new VerticalPanel();
		dockPanel.add(verticalPanel, DockPanel.CENTER);
		verticalPanel.setStyleName("menu");
		verticalPanel.setWidth("140");

		hyperlink = new Hyperlink("Imprezy", "Imprezy");
		verticalPanel.add(hyperlink);

		hyperlink_3 = new Hyperlink("Logowanie", "Login");
		verticalPanel.add(hyperlink_3);

		registerHyperlink = new Hyperlink("Zarejestruj", "Register");
		verticalPanel.add(registerHyperlink);

		disclosurePanel = new DisclosurePanel("Administracja");
		verticalPanel.add(disclosurePanel);
		disclosurePanel.setWidth("100%");

		verticalPanel_1 = new VerticalPanel();
		disclosurePanel.setContent(verticalPanel_1);
		verticalPanel_1.setWidth("100%");

		adminHyperlink = new Hyperlink("Admin Login", "AdminLogin");
		verticalPanel_1.add(adminHyperlink);

		hyperlink_1 = new Hyperlink("Dodaj Imprezę", "AddImpreza");
		verticalPanel_1.add(hyperlink_1);

		hyperlink_2 = new Hyperlink("Spis Kientów", "Kielnci");
		verticalPanel_1.add(hyperlink_2);


		centerPanel = new SimplePanel();
		dockPanel.add(centerPanel, DockPanel.EAST);
		centerPanel.setStyleName("zawartoscstrony");

		History.addHistoryListener(this);
		onHistoryChanged( History.getToken());
		showLogin();
	}

	public void onHistoryChanged(String historyToken) {

		if(isLogined) showLogin();
		if(historyToken.equals("Imprezy"))
		{
			goImprezy();
		}
		else if(historyToken.equals("Register"))
		{
			goRegister();
		}
		else if(historyToken.equals("Login"))
		{
			refergoto = "Logined";
			goLogin();
		}
		else if(historyToken.equals("MustLogin"))
		{
			VerticalPanel v = new VerticalPanel();
			centerPanel.setWidget(v);
			v.add(new Label("Musisz się zalogwać:"));
			v.add(new LoginForm());
		}
		else if(historyToken.equals("Logined"))
		{
			centerPanel.setWidget(new HTML("<p>Zostałeś zalogowany</p>"));
			showLogin();
		}
		else if(historyToken.equals("Logout"))
		{
			goLogout();
		}
		else if(historyToken.equals("AddImpreza")){
			goAddImpreza();
		}
		else if(historyToken.equals("AdminLogin")){
			goAdminLogin();
		}
		else if(historyToken.equals("Kielnci")){
			 goKielnci();
		}
		else 
		{
			centerPanel.setWidget(new HTML("<p>Opis</p>"));
		}
		
	}
	
	private void goKielnci()
	{
		if(isAdmin){
			centerPanel.setWidget(new Kielnci());
		}
		else
		{
			needLogin("Kielnci");
		}
	}
	
		
	private void needLogin(String refer)
	{
		refergoto = refer;
		VerticalPanel v = new VerticalPanel();
		centerPanel.setWidget(v);
		v.add(new Label("Musisz się zalogwać:"));
		v.add(new AdminLoginForm("Zaloguj"));
	}
		
	private void goAddImpreza() {
		if(isAdmin){
			centerPanel.setWidget(new AddImprezyForm());
		}
		else
		{
			needLogin("AddImpreza");
		}
	}

	private void showLogout(Label label)
	{
		isLogined = false;
		podpanel.clear();
		if(label==null)label = new Label("Jesteś niezalogowany");
		podpanel.add(label);
		podpanel.add(new Hyperlink("Logowanie Klienta", "Login"));
	}
	
	private void showLogin()
	{
		if(! isLogined)
		{
			podpanel.clear();
			final Label label = new Label("Trwa odświerzanie informacji");
			podpanel.add(label);
		}
		Server.Util.getInstance().getKlient(null, new GetLoginInfo());
	}
	
	private void goLogout() {
		// TODO Auto-generated method stub
		isAdmin = false;
		centerPanel.setWidget(new HTML("<p>Wylogowywanie...</p>"));
		Server.Util.getInstance().doLogout( 
			new AsyncCallback(){
				public void onFailure(Throwable caught) {

				}
				public void onSuccess(Object result) {
					centerPanel.setWidget(new HTML("<p>Zostałeś wylogowany</p>"));
					showLogout(new Label("Dziękujemy, możesz zalogować się ponownie"));
				}
			});
		
	}

	public void goAdminLogin()
	{
		centerPanel.setWidget(new AdminLoginForm("Zaloguj"));
	}
	
	public void goRegister() {
		// TODO Auto-generated method stub
		centerPanel.setWidget(new RegisterForm());
		
	}

	public void goImprezy() {
		centerPanel.setWidget(new Imprezy());
	}


	public void goLogin() {
		centerPanel.setWidget(new LoginForm());
	}

	public void setAdminLogin()
	{
		isAdmin = true;
		podpanel.add(new Label("Zalogowałeś się jako administrator"));
		podpanel.add(new Hyperlink("Wyloguj", "Logout"));
	}
	
	public class AdminLoginForm extends AbstractForm implements AsyncCallback{

		private PasswordField pass;


		AdminLoginForm(String processname) {
			super(processname);

			pass = new PasswordField("Hasło",6,32);
			addField(pass);
		}


		public void doRequest() {
			Server.Util.getInstance().doAdminLogin(pass.getText(),this);

		}
		
		public void onFailure(Throwable caught) {
		     try {
			       throw caught;
		     } catch (IncompatibleRemoteServiceException e) {
		       // this client is not compatible with the server; cleanup and refresh the 
		       // browser
		    	 setError(e.toString());
		     } catch (InvocationException e) {
		       // the call didn't complete cleanly
		    	 setError("Błąd połączenia:"+e.toString());
		     } catch (SerializableException e) {
		       // one of the 'throws' from the original method
		    	 setError(e.getMessage());
		     } catch (Throwable e) {
		       // last resort -- a very unexpected exception
		    	 setError(e.getLocalizedMessage());
		     }
			
		}
		
		public void onSuccess(Object result) {
	        setAdminLogin();
	        if(refergoto!=null) History.onHistoryChanged(refergoto);
	        refergoto=null;
		}

	}
	
	class GetLoginInfo implements AsyncCallback{
		public void onFailure(Throwable caught) {
			String s;
			caught.printStackTrace();
			try {
			      throw caught;
			} catch (IncompatibleRemoteServiceException e) {
			  // this client is not compatible with the server; cleanup and refresh the 
			  // browser
				s=e.toString();
			} catch (InvocationException e) {
			  // the call didn't complete cleanly
				s="Błąd połączenia:"+e.toString();
			 e.printStackTrace();
			} catch (SerializableException e) {
			  // one of the 'throws' from the original method
				s=e.getMessage();
			} catch (Throwable e) {
			  // last resort -- a very unexpected exception
				s=e.getLocalizedMessage();
			}
			final Label label = new Label(s);
			label.setStyleName("gwt-Label-Error");
			showLogout(label);
		}


		public void onSuccess(Object result) {
			// TODO Auto-generated method stub
			Server.KlientData klient = (KlientData) result;
			if(klient==null){
				showLogout(null);
				return;
			}
			podpanel.clear();
			String s = "Witaj "+klient.name+" "+klient.familyName;
			if(klient.bill.floatValue()>0.0)
				s+= " twój rachunek to "+klient.bill+"zł.";
			else
				s+= " nie posiadasz rachunków.";
			final Label label = new Label(s);
			isLogined = true;
			isAdmin = false;
			podpanel.add(label);
			podpanel.add(new Hyperlink("Wyloguj", "Logout"));
		}
	}
	

	
}
